Skip to content

feat(postgrest): add automatic retries for transient errors - #2072

Merged
mandarini merged 12 commits into
masterfrom
grdsdev/postgrest-auto-retry
Apr 2, 2026
Merged

mandarini merged 12 commits into
masterfrom
grdsdev/postgrest-auto-retry

Conversation

@grdsdev

@grdsdev grdsdev commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

What changed?

Adds automatic retry logic to @supabase/postgrest-js for two classes of transient errors:

  • 520 errors (Cloudflare timeout/connection errors under load) — ephemeral and safe to retry
  • 503 errors (PostgREST PGRST002 schema cache loading on a replica) — PostgREST explicitly signals retryability; when a Retry-After header is present, its value is used as the delay

Implementation details:

  • Retries are enabled by default for GET/HEAD/OPTIONS requests (idempotent methods only)
  • Up to 3 retry attempts with exponential backoff (1s, 2s, 4s, capped at 30s)
  • Network errors are also retried for idempotent methods
  • Response body is drained before each retry to prevent stream leaks
  • AbortError is rethrown immediately without retrying
  • Backoff sleeps respect the AbortSignal — aborting mid-wait resolves immediately
  • X-Retry-Count request header is added on retry attempts (requested by PostgREST author for observability)
  • Simple boolean API to control retries globally or per-request

New retry option on PostgrestClient:

// Retries enabled by default - no configuration needed
const { data, error } = await supabase.from('users').select()

// Disable retries globally
const client = new PostgrestClient('https://api.example.com', {
  retry: false,
})

// Disable retries per-request
const { data, error } = await supabase
  .from('users')
  .select()
  .retry(false)

// Re-enable per-request when globally disabled
const { data, error } = await supabase
  .from('users')
  .select()
  .retry(true)

Key design decisions:

Decision Rationale
Enabled by default Gives perception of more reliable service without opt-in friction
Only GET/HEAD/OPTIONS Non-idempotent methods (POST/PATCH/DELETE) could cause data duplication
520 + 503 520 = Cloudflare transient; 503 = PostgREST schema cache loading
Respects Retry-After header PostgREST sends Retry-After: 0 for PGRST002 — no unnecessary delay
X-Retry-Count header Requested by PostgREST author for server-side observability of retry storms
AbortError not retried User explicitly cancelled; retrying would violate intent
Abort respected during backoff Aborting mid-sleep resolves immediately instead of waiting the full delay
Body drained before retry Avoids stream leaks on retried responses

Why was this change needed?

Customers using load-balanced Supabase URLs and Cloudflare-fronted deployments experience intermittent failures that are safe to retry automatically. Without retries, these transient errors surface as real failures, making PostgREST appear unreliable even though the underlying request would succeed on a second attempt.

Screenshots/Examples

N/A

Breaking changes

  • This PR contains no breaking changes

Checklist

  • I have read the Contributing Guidelines
  • My PR title follows the conventional commit format: <type>(<scope>): <description>
  • I have run npx nx format to ensure consistent code formatting
  • I have added tests for new functionality (if applicable)
  • I have updated documentation (if applicable)

@github-actions github-actions Bot added the postgrest-js Related to the postgrest-js library. label Jan 29, 2026
@coderabbitai

coderabbitai Bot commented Jan 29, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • ✅ Full review completed - (🔄 Check again to review again)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/core/postgrest-js/src/PostgrestBuilder.ts`:
- Around line 193-244: The retry loop in executeWithRetry currently retries on
520 responses without consuming the response body and also may retry on
AbortError; update executeWithRetry so that when shouldRetry(...) returns true
you first fully drain the response body (e.g., await res.arrayBuffer() or
res.text() to consume streams) before sleeping/retrying, and in the catch block
immediately rethrow if fetchError.name === 'AbortError' (do not treat as
retryable), otherwise keep existing logic using RETRYABLE_METHODS,
DEFAULT_MAX_RETRIES, getRetryDelay, sleep, and continue calling _fetch and
processResponse as before.
🧹 Nitpick comments (3)
packages/core/postgrest-js/test/retry.test.ts (1)

210-235: Consider a more robust approach for verifying backoff delays.

The current implementation spies on setTimeout and immediately executes callbacks with delay=0. While functional, this approach bypasses the actual timing behavior and could mask issues if the retry implementation changes how it schedules delays.

A more robust alternative would use vi.getTimerCount() or advance timers by specific amounts and verify fetch call counts at each interval.

packages/core/postgrest-js/src/PostgrestQueryBuilder.ts (2)

24-25: Add JSDoc documentation for the retry property.

The retry property is part of the public API but lacks JSDoc documentation. Other public properties in this class could benefit from similar documentation, but at minimum the new retry property should be documented to explain its purpose and default behavior.

📝 Suggested documentation
+  /**
+   * Enable or disable automatic retries for transient errors.
+   * When enabled, idempotent requests (GET/HEAD/OPTIONS) that fail with 520 errors
+   * will be automatically retried with exponential backoff.
+   */
   // Retry configuration
   retry?: boolean

As per coding guidelines: "Use JSDoc comments for all public APIs in each library".


40-59: Add retry parameter to the constructor's JSDoc.

The constructor example and parameter documentation should include the new retry option for completeness.

📝 Suggested documentation update
   /**
    * Creates a query builder scoped to a Postgres table or view.
    *
    * `@example`
    * ```ts
    * import PostgrestQueryBuilder from '@supabase/postgrest-js'
    *
    * const query = new PostgrestQueryBuilder(
    *   new URL('https://xyzcompany.supabase.co/rest/v1/users'),
-   *   { headers: { apikey: 'public-anon-key' } }
+   *   { headers: { apikey: 'public-anon-key' }, retry: true }
    * )
    * ```
+   *
+   * `@param` url - The URL for the query
+   * `@param` options - Named parameters
+   * `@param` options.headers - Custom headers
+   * `@param` options.schema - Postgres schema
+   * `@param` options.fetch - Custom fetch function
+   * `@param` options.retry - Enable automatic retries for transient errors
    */

@pkg-pr-new

pkg-pr-new Bot commented Mar 27, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@supabase/auth-js

npm i https://pkg.pr.new/@supabase/auth-js@2072

@supabase/functions-js

npm i https://pkg.pr.new/@supabase/functions-js@2072

@supabase/postgrest-js

npm i https://pkg.pr.new/@supabase/postgrest-js@2072

@supabase/realtime-js

npm i https://pkg.pr.new/@supabase/realtime-js@2072

@supabase/storage-js

npm i https://pkg.pr.new/@supabase/storage-js@2072

@supabase/supabase-js

npm i https://pkg.pr.new/@supabase/supabase-js@2072

commit: 0f5b1b3

@mandarini
mandarini force-pushed the grdsdev/postgrest-auto-retry branch 2 times, most recently from 274617c to 7f6bc9b Compare March 27, 2026 14:32
@mandarini mandarini self-assigned this Mar 27, 2026
@mandarini
mandarini marked this pull request as ready for review March 27, 2026 14:42
@mandarini
mandarini requested review from a team as code owners March 27, 2026 14:42
Copilot AI review requested due to automatic review settings March 27, 2026 14:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@steve-chavez

Copy link
Copy Markdown
Member

Note: The X-Retry-Count diagnostic header was intentionally omitted from this PR to avoid CORS preflight issues with static Access-Control-Allow-Headers configs. It will be introduced in a future PR alongside an update to cors.ts.

The lack of retry header is concerning, without a retry header it will be too hard to debug at the origin server. Can that be added in this PR?

@mandarini

Copy link
Copy Markdown
Contributor

@steve-chavez I was worried about breaking changes. Since we now have https://supabase.com/docs/guides/functions/cors we can rely on this and hope users will be using it. I will add back the headers. Any thoughts about the 5xx errors?

@mandarini
mandarini force-pushed the grdsdev/postgrest-auto-retry branch from 30c0fc8 to 1096c54 Compare March 30, 2026 11:46
steve-chavez
steve-chavez previously approved these changes Mar 30, 2026

@steve-chavez steve-chavez left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

503 and 520 LGTM to retry on.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated 8 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/core/supabase-js/src/cors.ts Resolved
Implement automatic retry logic for PostgREST SDK requests that fail
with 520 status codes (Cloudflare timeout/connection errors).

Key features:
- Enabled by default for GET/HEAD/OPTIONS requests
- 3 retry attempts with exponential backoff (1s, 2s, 4s)
- X-Retry-Count header sent for observability
- Can be disabled globally or per-request via .retry(false)

This addresses customer feedback about perceived reliability issues
when transient 520 errors occur under load.

Related: https://linear.app/supabase/project/automatic-retries-for-postgrest-sdk-c6fa4eaf163a

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@mandarini
mandarini merged commit ea3e086 into master Apr 2, 2026
38 checks passed
@mandarini
mandarini deleted the grdsdev/postgrest-auto-retry branch April 2, 2026 10:33
mandarini pushed a commit to supabase/ssr that referenced this pull request Apr 7, 2026
This PR updates `@supabase/supabase-js` to v2.102.1.

**Source**: supabase-js-stable-release

---

## Release Notes

## v2.102.1

## 2.102.1 (2026-04-07)

### 🩹 Fixes

- **functions:** add toJSON to FunctionsError for correct JSON
serialization
([#2226](supabase/supabase-js#2226))

### ❤️ Thank You

- oniani1
## v2.102.0

## 2.102.0 (2026-04-07)

### 🚀 Features

- **postgrest:** add automatic retries for transient errors
([#2072](supabase/supabase-js#2072))
- **postgrest:** add success discriminator field to PostgREST response
types ([#2198](supabase/supabase-js#2198))
- **supabase:** export PostgrestFilterBuilder and StorageApiError from
supabase-js ([#2222](supabase/supabase-js#2222))

### 🩹 Fixes

- **auth:** downgrade console.error to console.warn for missing session
([#2214](supabase/supabase-js#2214))
- **ci:** add --ignore-scripts to platform test installs to block post
install attacks
([#2206](supabase/supabase-js#2206))
- **postgrest:** add toJSON to PostgrestError for correct JSON
serialization
([#2212](supabase/supabase-js#2212))
- **postgrest:** reject excess properties in insert, update, and upsert
([#2186](supabase/supabase-js#2186))
- **storage:** set correct content-type for uploads
([#2211](supabase/supabase-js#2211))
- **storage:** avoid duplicate content-type headers in vector requests
([#2220](supabase/supabase-js#2220))

### ❤️ Thank You

- Clay
- Guilherme Souza
- Katerina Skroumpelou @mandarini
- oniani1
- Vaibhav @7ttp

This PR was created automatically.

Co-authored-by: supabase-workflow-trigger[bot] <266661614+supabase-workflow-trigger[bot]@users.noreply.github.com>
mandarini pushed a commit to supabase/supabase that referenced this pull request Apr 7, 2026
This PR updates @supabase/*-js libraries to version 2.102.1.

**Source**: supabase-js-stable-release

**Changes**:
- Updated @supabase/supabase-js to 2.102.1
- Updated @supabase/auth-js to 2.102.1
- Updated @supabase/realtime-js to 2.102.1
- Updated @supabase/postgest-js to 2.102.1
- Refreshed pnpm-lock.yaml

---

## Release Notes

## v2.102.1

## 2.102.1 (2026-04-07)

### 🩹 Fixes

- **functions:** add toJSON to FunctionsError for correct JSON
serialization
([#2226](supabase/supabase-js#2226))

### ❤️ Thank You

- oniani1
## v2.102.0

## 2.102.0 (2026-04-07)

### 🚀 Features

- **postgrest:** add automatic retries for transient errors
([#2072](supabase/supabase-js#2072))
- **postgrest:** add success discriminator field to PostgREST response
types ([#2198](supabase/supabase-js#2198))
- **supabase:** export PostgrestFilterBuilder and StorageApiError from
supabase-js ([#2222](supabase/supabase-js#2222))

### 🩹 Fixes

- **auth:** downgrade console.error to console.warn for missing session
([#2214](supabase/supabase-js#2214))
- **ci:** add --ignore-scripts to platform test installs to block post
install attacks
([#2206](supabase/supabase-js#2206))
- **postgrest:** add toJSON to PostgrestError for correct JSON
serialization
([#2212](supabase/supabase-js#2212))
- **postgrest:** reject excess properties in insert, update, and upsert
([#2186](supabase/supabase-js#2186))
- **storage:** set correct content-type for uploads
([#2211](supabase/supabase-js#2211))
- **storage:** avoid duplicate content-type headers in vector requests
([#2220](supabase/supabase-js#2220))

### ❤️ Thank You

- Clay
- Guilherme Souza
- Katerina Skroumpelou @mandarini
- oniani1
- Vaibhav @7ttp
## v2.101.1

## 2.101.1 (2026-03-31)

### 🩹 Fixes

- **storage:** support exactOptionalPropertyTypes
([#2200](supabase/supabase-js#2200))

### ❤️ Thank You

- Vaibhav @7ttp

This PR was created automatically.

Co-authored-by: supabase-workflow-trigger[bot] <266661614+supabase-workflow-trigger[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

postgrest-js Related to the postgrest-js library.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants